// miniprogram/pages/admin/category/categoryList.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    value: "",
    _id: undefined,
    buttons: [
        {
            type: 'primary',
            className: '',
            text: '保存',
            value: 1
        }
    ],
    list:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCategoryList();
  },
  open: function () {
    this.setData({
        show: true
    })
  },
  close: function() {
    this.setData({
        show: false
    })
  },
  buttontap(e) {
    console.log(e.detail,'保存', this.data.value);
    this.saveCategory();
  },
  inputHandel(e) {
    this.setData({
      value: e.detail.value
    })
  },
  getCategoryList() {
    const that = this;
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'categoryApi',
      // 传给云函数的参数
      data: {
        method: "queryList",
        args: {}
      },
      // 成功回调
      complete: (res)=>{
        console.log(res);
        that.setData({
          list: res.result.rstData.data
        });
      }
    })
  },
  saveCategory(){
    const that = this;
    let methodName = "addCategory";
    let param = {name: this.data.value};
    if(this.data._id) {
      methodName = "updateCategory";
      param._id = this.data._id;
    }
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'categoryApi',
      // 传给云函数的参数
      data: {
        method: methodName,
        args: param
      },
      // 成功回调
      complete: (res)=>{
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 1000
        });
        that.getCategoryList();
        that.close();
      }
    })
  },
  add() {
    this.setData({
      _id: "",
      value: ""
    });
    this.open();
  },
  update(e) {
    this.setData({
      _id: e.currentTarget.dataset.id,
      value: e.currentTarget.dataset.name
    });
    this.open();
  },
  delete(e) {
    const that = this;
    let param = {_id: e.currentTarget.dataset.id};
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'categoryApi',
      // 传给云函数的参数
      data: {
        method: "delCategory",
        args: param
      },
      // 成功回调
      complete: (res)=>{
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 1000
        });
        that.getCategoryList();
      }
    })
  }
})